package com.niodata.dp.monitor.components.task.monitor;

import com.niodata.dp.monitor.components.task.dao.TaskExecHourCountMapper;
import com.niodata.dp.monitor.components.task.dao.TaskExecStatisticMapper;
import com.niodata.dp.monitor.sharelib.entity.monitor.task.TaskExecHourCount;
import com.niodata.dp.monitor.sharelib.entity.monitor.task.TaskExecHourStatistic;
import com.niodata.dp.util.TimeUtil;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Service
public class TaskExecHourCountJob implements Job {

  private static Logger logger = Logger.getLogger(TaskExecHourCountJob.class);
  @Autowired
  TaskExecHourCountMapper taskExecHourCountMapper;
  @Autowired
  TaskExecStatisticMapper execStatisticMapper;

  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

    logger.info("TaskExecHourCountJob start ...");
    Calendar end = Calendar.getInstance();
    end.add(Calendar.HOUR_OF_DAY, -1);
    end.set(Calendar.MINUTE, 59);
    end.set(Calendar.SECOND, 59);
    Date endTime = end.getTime();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //获取最大时间
    Date startTime = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String maxTime = taskExecHourCountMapper.getMaxDataTime();
    if (StringUtils.isBlank(maxTime)) {
      Calendar start = Calendar.getInstance();
      start.add(Calendar.YEAR, -1);
      startTime = start.getTime();
    } else {
      try {
        startTime = sdf.parse(maxTime + "0000");
        startTime = DateUtils.addHours(startTime, 1);
        //如果数据库中的最大数据时间与当前时间相差小于60，则是上一个已经统计过的时间，跳过

        logger.info("统计每小时task执行次数,startTime:"
              + format.format(startTime) + ",endTime:" + format.format(endTime));
        logger.info("时间间隔：" + TimeUtil.minutesBetween(endTime, startTime));
      } catch (ParseException e) {
        e.printStackTrace();
        return;
      }
    }

    //执行查询语句
    List<TaskExecHourStatistic> execHourStatisticList
          = execStatisticMapper.getExecHourCount(startTime, endTime);
    if (null == execHourStatisticList || execHourStatisticList.size() < 1) {
      logger.info("execHourStatisticList is null.");
      return;
    }

    List<TaskExecHourCount> taskExecCountList = buildNewTaskExecHourCount(execHourStatisticList);
    if (null == taskExecCountList || taskExecCountList.size() < 1) {
      logger.info("统计每小时task执行次数," + "总条数：0" + ",startTime:"
            + format.format(startTime) + ",endTime:" + format.format(endTime));
      return;
    }

    List<TaskExecHourCount> reslutList = new ArrayList<>();
    for (TaskExecHourCount execHourCount : taskExecCountList) {
      if (!StringUtils.isBlank(maxTime)) {
        if (execHourCount.getDataTime().equals(maxTime)) {
          continue;
        }
      }
      reslutList.add(execHourCount);
    }

    taskExecHourCountMapper.insert(reslutList);
    logger.info("统计每小时task执行次数结束," + "总条数："
          + taskExecCountList.size() + ",startTime:"
          + format.format(startTime) + ",endTime:" + format.format(endTime));

  }

  public List<TaskExecHourCount> buildNewTaskExecHourCount(
        List<TaskExecHourStatistic> execStatisticList) {
    Date now = new Date();
    List<TaskExecHourCount> execCountList = new ArrayList<>();
    for (TaskExecHourStatistic execDay : execStatisticList) {
      TaskExecHourCount taskExecCount = new TaskExecHourCount();
      taskExecCount.setId(uuid());
      taskExecCount.setCreateTime(new Timestamp(now.getTime()));
      taskExecCount.setOwnerId(execDay.getOwnerId());
      taskExecCount.setOwnerType(execDay.getOwnerType());
      taskExecCount.setExecCount(execDay.getExecCount());
      taskExecCount.setExecSucceeded(execDay.getExecSucceeded());
      taskExecCount.setExecFailed(execDay.getExecFailed());
      taskExecCount.setDataTime(execDay.getDataTime());
      execCountList.add(taskExecCount);
    }
    return execCountList;
  }

  public String uuid() {
    return UUID.randomUUID().toString().replaceAll("-", "");
  }


}
